package com.ishopping.web.manage.controller;

import com.github.pagehelper.PageInfo;
import com.ishopping.common.core.base.constant.CommonConstants;
import com.ishopping.common.core.base.controller.BaseController;
import com.ishopping.api.manage.entity.User;
import com.ishopping.api.manage.entity.UserRole;
import com.ishopping.api.manage.service.IUserRoleService;
import com.ishopping.api.manage.service.IUserService;
import com.ishopping.common.core.base.enums.ReturnEnum;
import com.ishopping.common.core.vo.DataGridResult;
import com.ishopping.common.core.vo.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户controller
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    /**
     * 默认页面
     */
    @RequiresPermissions("system:user:manage")
    @RequestMapping(value = "/manage", method = RequestMethod.GET)
    public String userManager() {
        return "system/userMgt";
    }

    /**
     * 获取用户列表
     */
    @RequestMapping(value="/list",method = RequestMethod.GET)
    @ResponseBody
    @RequiresPermissions("system:user:manage")
    public ResponseEntity<DataGridResult> userList(HttpServletRequest request, User user) {
        try {
            int currentPage = Integer.valueOf(request.getParameter("page"));
            int pageSize = Integer.valueOf(request.getParameter("rows"));
            Long orgId = user.getOrgId();
            if(orgId == null) {
                //return new PageInfo();
            }
            PageInfo page = userService.queryPageListByWhere(user, currentPage, pageSize);
            DataGridResult dataGrid = new DataGridResult(page.getTotal(), page.getList());
            return ResponseEntity.ok(dataGrid);
        } catch (Exception e) {
            LOGGER.error("查询角色列表出错!" , e);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }

    /**
     * 添加用户跳转
     * @param model
     */
    @RequiresPermissions("system:user:add")
    @RequestMapping(value = "/addForm", method = RequestMethod.GET)
    public String addUserForm(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("action", CommonConstants.ADD);
        return "system/userForm";
    }

    /**
     * 添加用户
     * @param user
     */
    @RequiresPermissions("system:user:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object addUser(User user) {
        int result = userService.doSave(user);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 修改用户跳转
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("system:user:update")
    @RequestMapping(value = "/updateForm/{id}", method = RequestMethod.GET)
    public String updateUserForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("user", userService.queryById(id));
        model.addAttribute("action", CommonConstants.UPDATE);
        return "system/userForm";
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateUser(User user) {
        int result = userService.updateSelective(user);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequiresPermissions("system:user:delete")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object deleteUser(@PathVariable("id") Long id) {
        int result = userService.deleteById(id);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 用户添加角色跳转
     * @param model
     * @param userId
     * @return String
     */
    @RequiresPermissions("system:user:assignRole")
    @RequestMapping(value = "/{userId}/assignRoleForm")
    public String getUserRole(Model model, @PathVariable("userId") Long userId) {
        model.addAttribute("userId", userId);
        return "system/assignRole";
    }

    /**
     * 修改用户拥有的角色
     * @param userId
     * @param newRoleList
     * @return
     */
    @RequiresPermissions("system:user:assignRole")
    @RequestMapping(value = "/{userId}/assignRole")
    @ResponseBody
    public Object updateUserRole(@PathVariable("userId") Long userId, @RequestBody List<Long> newRoleList) {
        int result = userRoleService.save(userId, newRoleList);
        if(result > 0) {
            return JsonResult.success();
        }else{
            return JsonResult.build(ReturnEnum.USER_FAIL.getValue(), ReturnEnum.USER_FAIL.getText());
        }
    }

    /**
     * 获取用户拥有的角色
     * @param userId
     * @return String
     */
    @RequiresPermissions("system:user:assignRole")
    @RequestMapping(value = "/{userId}/role")
    @ResponseBody
    public List<UserRole> getUserRoleList(@PathVariable("userId") Long userId) {
        return userRoleService.findUserRolesByUserId(userId);
    }

    /**
     * Ajax请求校验username是否唯一。
     */
    @RequestMapping(value = "/checkUsername")
    @ResponseBody
    public String checkLoginName(HttpServletRequest request) {
        String username = request.getParameter("username");
        if(StringUtils.isBlank(username)){
            return CommonConstants.FALSE;
        }
        User u = new User();
        u.setUsername(username);
        User user = userService.queryOne(u);
        if (user == null) {
            return CommonConstants.TRUE;
        } else {
            return CommonConstants.FALSE;
        }
    }
}
